package com.oamicnet;

import com.oamicnet.entity.Student;
import com.oamicnet.service.StudentServiceImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Hello world!
 *
 */
public class CglibProxyApp
{
    public static void main( String[] args )
    {
        Student student = new Student();
        student.setId(1);
        student.setName("John");
        student.setEmail("oamicnet@gmail.com");

        // 只需引入 cglib 依赖，Spring AOP 已内置
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(StudentServiceImpl.class);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                // 方法调用前增强
                System.out.println("方法调用前，参数：" + args[0]);
                Object result = proxy.invokeSuper(obj, args);
                // 方法调用后增强
                System.out.println("方法调用后");
                return result;
            }
        });
        StudentServiceImpl proxy = (StudentServiceImpl) enhancer.create();

        // 调用代理对象的方法
        proxy.save(student);

        proxy.update(student);
    }
}
